package v2ray

import (
	"context"
	"gitee.com/Luna-CY/hui-hui/internal/application/v2ray"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"gitee.com/Luna-CY/hui-hui/server/http/response"
	"github.com/gin-gonic/gin"
)

type SetOutboundFreedomRequest struct {
	BaseBoundRequest
	BaseOutboundRequest

	DomainStrategy string                    `json:"domain_strategy" validate:"optional" enums:"AsIs,UseIP,UseIPv4,UseIPv6" binding:"omitempty,oneof=AsIs UseIP UseIPv4 UseIPv6"` // 转发模式
	Redirect       string                    `json:"redirect" validate:"optional" binding:"omitempty"`                                                                            // 不为空时强制重定向到此地址
	UserLevel      int                       `json:"user_level" validate:"optional" binding:"omitempty"`                                                                          // 用户级别
	StreamSettings BaseStreamSettingsRequest `json:"stream_settings" validate:"optional" binding:"omitempty,dive"`                                                                // 传输配置
}

func (cls *V2ray) SetOutboundFreedom(c *gin.Context) (int, any, error) {
	var body = SetOutboundFreedomRequest{DomainStrategy: "AsIs"}
	if err := c.ShouldBindJSON(&body); nil != err {
		return response.InvalidRequest, nil, err
	}

	var ctx = context.Background()

	var protocol, err = v2ray.NewFreedomOutbound(body.Id, body.Tag, body.OutboundSendThrough, application.V2rayFreedomDomainStrategy(body.DomainStrategy), body.Redirect, body.UserLevel, body.StreamSettings.build())
	if nil != err {
		return response.InvalidRequest, nil, err
	}

	if err := cls.v2ray.SetOutbound(ctx, protocol.Id, protocol); nil != err {
		return response.Unknown, nil, err
	}

	// 应用配置
	if err := cls.v2ray.ApplyConfig(ctx); nil != err {
		return response.Unknown, nil, err
	}

	return response.Ok, nil, nil
}
